const { Add, Update, QueryById, Query, Exec, Execsql_Count, ExecGetOne, Exec_Count } = require('../db/dbhelper');
var _ = require('underscore');
var { formatDate, formatDateTime, formatDateYear } = require('../libs/common');
const logger = require('../libs/log').logger;
var moment = require('moment');

const matchhistoryQueryOne = async function (doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: 'id参数不能为空'
      }
    }
    let data = await QueryById('hzz_matchhistories', doc.id);
    let pObj_sql = `SELECT code,name,nickname,avator,age,grender,birthday,star,height,signature,education FROM hzz_peoples WHERE CODE=${data.pcode} `;
    let matchObj_sql = `SELECT code,name,nickname,avator,age,grender,birthday,star,height,signature,education FROM hzz_peoples WHERE CODE=${data.matchcode} `;
    let pObj = await Exec(pObj_sql);
    // 用户没有头像，采用默认头像
    if (!pObj.avator) {
      pObj.avator = pObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
    }
    let matchObj = await Exec(matchObj_sql);
    // 用户没有头像，采用默认头像
    if (!matchObj.avator) {
      matchObj.avator = matchObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
    }
    data.pinfo = pObj;
    data.minfo = matchObj;
    data.createtime = formatDateTime(data.createtime);
    delete data.updatetime;
    return {
      code: 0,
      data: data
    };
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

// 列表
const matchhistoryList = async function (req) {
  try {
    let { userphone, userrole } = req.headers;
    let isenterprise = userrole ? userrole.split(',').includes('enterprise') : false;
    let isadmin = userrole ? userrole.split(',').includes('hzzadmin') || userrole.split(',').includes('administrators') || userrole.split(',').includes('OperationUser'): false;
    let { pcode, pagenum, pagesize, activedes, active, Filter } = req.body;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let exec_sql = 'select id,pcode,visitcode,matchcode,visitmatchcode,active,activedes,createtime from hzz_matchhistories WHERE 1=1 ';
    let exec_qlCount = 'select count(1) as total from hzz_matchhistories WHERE 1=1 ';
    let filter_sql = '';
     // 如果是外联合作推荐人角色，并且绑定手机号的，只查询自己用户信息
     if(isenterprise && userphone){
      let da1= await ExecGetOne(`select pcode from hzz_inviterhistories where phone ='${userphone}'`);
      if(da1){
        pcode=da1.pcode;
      }
    }
    if (pcode) {
      filter_sql = `  AND (visitcode='${pcode}'  OR visitmatchcode='${pcode}')  `;
    }
    if (activedes) {
      filter_sql += ` AND activedes='${activedes}' `;
    }
    if (active) {
      filter_sql += ` AND active=${active} `;
    }
    if (Filter && Filter.activedes) {
      filter_sql += ` AND activedes='${Filter.activedes}' `;
    }
    if (Filter && Filter.active) {
      filter_sql += ` AND active=${Filter.active} `;
    }
    if (Filter && Filter.nickname) {
      let peoList = await Exec(`select code from hzz_peoples where nickname like '%${Filter.nickname}%' or name like '%${Filter.nickname}%' or name_father like '%${Filter.nickname}%'`)
      if (peoList && peoList.length) {
        peoList = _.pluck(peoList, 'code')
        filter_sql += ` AND (pcode IN (${peoList.join(',')}) OR matchcode IN (${peoList.join(',')}))`;
      }
    }
    if(Filter && Filter.invitcode){
      filter_sql += ` AND ( visitcode=${Filter.invitcode} OR visitmatchcode=${Filter.invitcode}) `;
    }
    filter_sql += ` AND length(visitcode)=12 AND length(visitmatchcode)=12 AND length(pcode)=12 AND length(matchcode)=12 `;

    exec_sql += filter_sql;
    exec_qlCount += filter_sql;
    exec_sql += ' ORDER BY createtime DESC,id ASC'
    exec_sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let data = await Exec(exec_sql);
    let peos = [];
    if (data.length) {
      let codestr = _.compact(_.union(_.pluck(data, 'pcode'), _.pluck(data, 'matchcode'), _.pluck(data, 'visitcode'), _.pluck(data, 'visitmatchcode'))).join(',');
      let execsql = 'SELECT name,nickname,phone,code,avator,state,grender,birthday,education,city,province_town,height,position FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }

    let list = [];
    for (let index = 0; index < data.length; index++) {
      let item = data[index];
      let find = _.find(list, function (fl) {
        return fl.pcode == item.matchcode && fl.matchcode == item.pcode;
      })
      if (!find) {
        let pp1 = _.find(peos, function (po) {
          return po.code == item.pcode;
        })
        let pObj = pp1 ? JSON.parse(JSON.stringify(pp1)) : null;
        if (pObj) {
          pObj.birthday = formatDateYear(pObj.birthday);
          pObj.city = pObj.city ? pObj.city.replace('市', '') : '';
          pObj.province_town = pObj.province_town ? pObj.province_town.replace('省', '人').replace('市', '人') : '';
          // 用户没有头像，采用默认头像
          if (pObj && !pObj.avator) {
            pObj.avator = pObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
          }
        }
        let pp2 = _.find(peos, function (po) {
          return po.code == item.matchcode;
        })
        let matchObj = pp2 ? JSON.parse(JSON.stringify(pp2)) : null;
        if (matchObj) {
          matchObj.birthday = formatDateYear(matchObj.birthday);
          matchObj.city = matchObj.city ? matchObj.city.replace('市', '') : '';
          matchObj.province_town = matchObj.province_town ? matchObj.province_town.replace('省', '人').replace('市', '人') : '';
          // 用户没有头像，采用默认头像
          if (matchObj && !matchObj.avator) {
            matchObj.avator = matchObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
          }
        }
        item.createtime = formatDateTime(item.createtime);
        item.pinfo = pObj || {};
        item.minfo = matchObj || {};

        let visitcodeObj = _.find(peos, function (po) {
          return po.code == item.visitcode;
        })
        // 用户没有头像，采用默认头像
        if (visitcodeObj && !visitcodeObj.avator) {
          visitcodeObj.avator = visitcodeObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
        if(isadmin){
          visitcodeObj.phone = visitcodeObj.phone? visitcodeObj.phone: '-';
        }else{
          visitcodeObj.phone = visitcodeObj.phone? visitcodeObj.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2"): '-';
        }
        
        item.visiter = visitcodeObj || {};
        let visitmatchcodeObj = _.find(peos, function (po) {
          return po.code == item.visitmatchcode;
        })
        // 用户没有头像，采用默认头像
        if (visitmatchcodeObj && !visitmatchcodeObj.avator) {
          visitmatchcodeObj.avator = visitmatchcodeObj.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
        if(isadmin){
          visitmatchcodeObj.phone = visitmatchcodeObj.phone? visitmatchcodeObj.phone: '-';
        }else{
          visitmatchcodeObj.phone = visitmatchcodeObj.phone? visitmatchcodeObj.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2"): '-';
        }
        item.visitmatcher = visitmatchcodeObj || {};
        // 更新消息已读状态
        if(!Filter){
          if (pcode == item.visitcode) {
            matchhistoryUpdate({ id: item.id, visread: 1 });
          }
          if (pcode == item.visitmatchcode) {
            matchhistoryUpdate({ id: item.id, misread: 1 });
          }
        }else{
            // 管理后台统计3日内发送消息数
            let sql_c= ` AND createtime >= '${moment().subtract(3,'day').format('YYYY-MM-DD HH:MM')}' AND createtime <= '${moment().format('YYYY-MM-DD HH:MM')}'`;
            item.count3 = await Execsql_Count(`select count(1) as total from hzz_immessages where ((senderId='${item.pcode}' AND receiverId='${item.matchcode}') OR (senderId='${item.matchcode}' OR receiverId='${item.pcode}')) `+sql_c);
            item.countA = await Execsql_Count(`select count(1) as total from hzz_immessages where senderId='${item.pcode}' AND receiverId='${item.matchcode}' `+sql_c);
            item.countB = await Execsql_Count(`select count(1) as total from hzz_immessages where senderId='${item.matchcode}' AND receiverId='${item.pcode}' `+sql_c);
        }
        
        list.push(item);
      }
    }
    let total = await Execsql_Count(exec_qlCount);

    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.error('---------matchhistoryList----error', error)
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

//修改
const matchhistoryUpdate = function (doc) {
  return Update('hzz_matchhistories', doc);
}

// 创建匹配记录
const matchhistoryAdd = async function (doc) {
  try {
    logger.info(`-------matchhistoryAdd------doc:`, doc)
    if (!doc.pcode || !doc.fcode) {
      logger.info(`-------matchhistoryAdd------pcode,fcode不能为空-----------`, doc)
      return;
    }
    // 判断是否配对过
    let ispd = await ExecGetOne(`select * from hzz_matchhistories where (pcode='${doc.pcode}' and matchcode='${doc.fcode}') OR (pcode='${doc.fcode}' and matchcode='${doc.pcode}')`);
    if (ispd) {
      logger.info(`-------matchhistoryAdd-----pcode:【${doc.pcode}】与fcode:【${doc.fcode}】已配对，本次不更新`);
      return;
    }
    let ppeople = await ExecGetOne(`select code,invitcode from hzz_peoples where code='${doc.pcode}'`);
    let matchpeople = await ExecGetOne(`select code,invitcode from hzz_peoples where code='${doc.fcode}'`);
    let newobj = {
      pcode: ppeople.code,
      visitcode: ppeople.invitcode,
      matchcode: matchpeople.code,
      visitmatchcode: matchpeople.invitcode,
      active: 1,
      activedes: '聊天中',
      createtime: new Date(),
      updatetime: new Date()
    };
    await Add('hzz_matchhistories', newobj);
  } catch (error) {
    logger.info(`-------matchhistoryAdd------error:`, error)
  }
}

// 定时更新用户推荐人code
const timerMatchInvistcode = async function () {
  let list = await Exec(`select id,pcode,matchcode,visitcode,visitmatchcode from hzz_matchhistories where visitcode is NULL or visitmatchcode is NULL`);
  for (const item of list) {
    let pdata = await ExecGetOne(`select code,invitcode from hzz_peoples where code='${item.pcode}'`);
    let mdata = await ExecGetOne(`select code,invitcode from hzz_peoples where code='${item.matchcode}'`);
    let updateDoc = {
      id: item.id
    };
    if (!item.visitcode) {
      updateDoc.visitcode = pdata.invitcode;
    }
    if (!item.visitmatchcode) {
      updateDoc.visitmatchcode = mdata.invitcode;
    }
    await Update('hzz_matchhistories', updateDoc);
  }
}

// 脱单
const edit_active = async function (doc) {
  try {
    logger.info(`-------edit_active------doc:`, doc)
    let { id, active } = doc;
    if (!id) {
      return {
        code: 1,
        msg: '请选择操作记录'
      };
    }
    if (!active) {
      return {
        code: 1,
        msg: '请选择配对状态'
      };
    }
    //0：解除配对 1： 聊天中、2： 取得联系、3：见面、4：确定关系
    if (active == 3) {
      await Exec(`UPDATE hzz_matchhistories SET active=3,activedes='线下交往' WHERE id=${id}`);
      return {
        code: 0,
        msg: '设置线下交往成功！'
      }
    } else if (active == 4) {
      await Exec(`UPDATE hzz_matchhistories SET active=4,activedes='确定关系' WHERE id=${id}`);
      return {
        code: 0,
        msg: '设置确定关系成功！'
      }
    } else if (active == 1) {
      await Exec(`UPDATE hzz_matchhistories SET active=1,activedes='聊天中' WHERE id=${id}`);
      return {
        code: 0,
        msg: '设置聊天中成功！'
      }
    } else if (active == 2) {
      await Exec(`UPDATE hzz_matchhistories SET active=2,activedes='取得联系' WHERE id=${id}`);
      return {
        code: 0,
        msg: '设置取得联系成功！'
      }
    } else {
      return {
        code: 1,
        msg: '设置失败，请联系客服！'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: '设置异常，请联系客服！'
    }
  }
}

module.exports = {
  matchhistoryUpdate,
  matchhistoryQueryOne,
  matchhistoryList,
  matchhistoryAdd,
  timerMatchInvistcode,
  edit_active,
}